#!/bin/bash

# 获取参数
GIT_BRANCH=$1
DEPLOY_DIR=$2
GIT_REPO_URL=$3

# 验证必要参数
if [ -z "$GIT_BRANCH" ] || [ -z "$DEPLOY_DIR" ] || [ -z "$GIT_REPO_URL" ]; then
  echo "错误：缺少必要参数"
  echo "用法: $0 <分支名> <部署目录> <仓库URL>"
  exit 1
fi

echo "[INFO] 部署分支: ${GIT_BRANCH}"
echo "[INFO] 部署目录: ${DEPLOY_DIR}"
echo "[INFO] 仓库地址: ${GIT_REPO_URL}"

# 创建或清空部署目录
if [ -d "$DEPLOY_DIR/.git" ]; then
  echo "[INFO] Git 仓库已存在，拉取最新代码..."
  cd "$DEPLOY_DIR" || { echo "[ERROR] 无法进入目录 $DEPLOY_DIR"; exit 1; }
  git checkout "$GIT_BRANCH" || { echo "[ERROR] 切换分支失败"; exit 1; }
  git pull origin "$GIT_BRANCH" || { echo "[ERROR] 拉取代码失败"; exit 1; }
else
  echo "[INFO] 目录不存在或不是 Git 仓库，准备重新克隆..."
  rm -rf "$DEPLOY_DIR"
  mkdir -p "$DEPLOY_DIR"
  cd "$(dirname "$DEPLOY_DIR")" || exit 1

  # 如果是 http(s)，转换为 SSH 地址
  if [[ $GIT_REPO_URL == http* ]]; then
    DOMAIN=$(echo "$GIT_REPO_URL" | sed -E 's|https?://([^/]+)/.*|\1|')
    REPO_PATH=$(echo "$GIT_REPO_URL" | sed -E 's|https?://[^/]+/(.+)|\1|')
    GIT_REPO_URL="git@${DOMAIN}:${REPO_PATH}"
    echo "[INFO] 已转换为 SSH 格式: $GIT_REPO_URL"
  fi

  echo "[INFO] 正在克隆仓库..."
  if ! git clone -b "$GIT_BRANCH" "$GIT_REPO_URL" "$(basename "$DEPLOY_DIR")"; then
    echo "[ERROR] 克隆仓库失败，请检查 SSH 密钥或仓库权限"
    exit 1
  fi
fi

# 设置 Git 仓库目录安全性（避免 safe.directory 警告）
git config --global --add safe.directory "$DEPLOY_DIR"

# 设置 Git 忽略权限变更
if [ -d "$DEPLOY_DIR/.git" ]; then
  cd "$DEPLOY_DIR" || exit 1
  git config core.fileMode false
else
  echo "[WARN] $DEPLOY_DIR 不是 Git 仓库，跳过 Git 设置"
fi

# 设置 Git 目录权限
chmod -R 755 "$DEPLOY_DIR/.git"

# 修改目录所有者（根据需要更改 www:www）
sudo chown www:www "$DEPLOY_DIR" -R

# 整个站点根目录权限改为 555
sudo chmod 555 "$DEPLOY_DIR" -R

# 对目录设置 555，文件设置 644（防止 git 判定文件变更）
find "$DEPLOY_DIR" -type d -exec chmod 555 {} \;
find "$DEPLOY_DIR" -type f -exec chmod 644 {} \;

# 确保 runtime 和 public/storage 目录存在
mkdir -p "$DEPLOY_DIR/runtime"
mkdir -p "$DEPLOY_DIR/public/uploads"

# 设置 writable 目录
chmod -R u+w "$DEPLOY_DIR/runtime"
chmod -R u+w "$DEPLOY_DIR/public/uploads"

# 若有配置文件，赋予写权限
if [ -f "$DEPLOY_DIR/config/pay.php" ]; then
  chmod -R u+w "$DEPLOY_DIR/config/pay.php"
fi

# 可选重启服务
# systemctl restart nginx
# systemctl restart php-fpm

echo "[SUCCESS] 部署完成 ✅"

# 可选删除本脚本（建议调试阶段先注释）
# rm -f "$0"
